package com.hanson.config;

import com.hanson.aop.interceptor.IpInterceptor;
import com.hanson.common.constant.Constant;
import com.hanson.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ResourceUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @program: manager
 * @description: mvc过滤器拦截配置
 * @param:
 * @author: Hanson
 * @create: 2020-09-08 12:58
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    StringToDateConverter stringToDateConverter;

    @Bean
    @Profile({Constant.ENVIROMENT_PRO,Constant.ENVIROMENT_TEST,Constant.ENVIROMENT_LOCAL})
    public HandlerInterceptor ipInterceptor(){
        return new IpInterceptor();
    }

    /*
    * 配置静态资源文件路径
    * @params: [registry]
    * @return: void
    * @throws: Exception
    * @Date: 2020/9/8
    */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**","/fonts/**","/lib/**","/js/**","/images/**")
                .addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/css/",
                        ResourceUtils.CLASSPATH_URL_PREFIX + "/fonts/",
                        ResourceUtils.CLASSPATH_URL_PREFIX + "/lib/",
                        ResourceUtils.CLASSPATH_URL_PREFIX + "/js/",
                        ResourceUtils.CLASSPATH_URL_PREFIX + "/images/");

    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {

    }

    /**
    *
    * 配置字符串转Date日期类型转换器并注册到SpringMvc中
    *
    * @params: [registry]
    * @param: registry
    * @since: 2021/1/6
    **/
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(stringToDateConverter);
    }

    /**
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String activeProfile = SpringContextUtil.getActiveProfile();
        if (Constant.ENVIROMENT_DEV.equals(activeProfile)) return;
        //添加拦截链，排除拦截链主要是避免SpringMVC转发时的新请求而重新执行拦截器内容，这是我不希望的
        registry.addInterceptor(ipInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/error","/logout","/unauth","/favicon.ico","/xxl-job-executor","/convey/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
